import logging
from django import http
from django.core.cache import cache

from django.shortcuts import render

# Create your views here.
from django.views import View

from areas.models import Area
from meiduo_mall.utils.response_code import RETCODE

logger = logging.getLogger('django')
class AreasView(View):
    '''设置省市区三级联动'''
    def get(self,request):
        '''判断当前查询的是省份数据还是市区数据'''

        area_id = request.GET.get('area_id')
        if not area_id:
            province_list = cache.get('province_list')
            if not province_list:
                try:
                    '''查询省份数据 Area.objects.filter = 属性名__条件表达式 = 值'''
                    province_model_list = Area.objects.filter(parent__isnull = True)
                    '''Json不能识别模型，所以要把模型转化成为字典列表'''
                    province_list = []
                    for province_model in province_model_list:
                        province_dict = {
                            'id' :province_model.id,
                            'name':province_model.name
                        }
                        province_list.append(province_dict)
                    '''缓存省份数据'''
                    cache.set('province_list',province_list,3600)
                except Exception as e:
                    logger.error(e)
                    return http.JsonResponse({'code':RETCODE.DBERR,'errmsg':'查询省份数据失败'})

            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'province_list': province_list})

        # '''查询市区数据'''
        else:
        # 先查询市或区的父级\
        # 读取市或区缓存数据
            sub_data = cache.get('sub_area_' + area_id)
            if not sub_data:
                try:
                    parent_model = Area.objects.get(id=area_id)
                    sub_model_list = parent_model.subs.all()
                # 序列化市或区数据
                    subs = []
                    # 将模型数据转化为字典列表
                    for sub_model in sub_model_list:
                        sub_dict = {
                            'id':sub_model.id,
                            'name':sub_model.name,
                        }
                        subs.append(sub_dict)
                        # 构造子级Json数据
                    sub_data = {
                        'id':parent_model.id,#父类的id
                        'name':parent_model.name,#父类的name
                        'subs':subs
                        }
                    cache.set('sub_area_' + area_id, sub_data, 3600)
                except Exception as e:
                    logger.error(e)
                    return http.JsonResponse({'code':RETCODE.DBERR,'errmsg':'查询城市数据失败'})
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'sub_data': sub_data})
